package com.virtualightning.mvvm.tools

import kotlinx.coroutines.CompletableDeferred

/**
 *  Anchor : Create by CimZzz
 *  Time : 2021/06/07 23:38:56
 *  Project : zxs-new
 *  Activity Result 结果 Deferred
 */
class ActivityResultDeferred<T> (
	val requestCode: Int,
	private val dataCls: Class<T>,
	private val completeDeferred: CompletableDeferred<T?>
) {
	///////////////////////////////////////////////////////////////////////////
	// Add by CimZzz on 2021/6/7 11:40 PM
	// 等待数据返回结果
	///////////////////////////////////////////////////////////////////////////
	suspend fun await() : T? {
		return completeDeferred.await()
	}

	///////////////////////////////////////////////////////////////////////////
	// Add by CimZzz on 2021/6/7 11:41 PM
	// 填充数据
	///////////////////////////////////////////////////////////////////////////
	internal fun feed(data: Any?) {
		if(dataCls.isInstance(data)) {
			completeDeferred.complete(dataCls.cast(data))
			return
		}
		completeDeferred.complete(null)
	}

	///////////////////////////////////////////////////////////////////////////
	// Add by CimZzz on 2021/10/12 11:43 AM
	// 取消 Deferred
	///////////////////////////////////////////////////////////////////////////
	internal fun cancel() {
		completeDeferred.complete(null)
	}
}